/**
 *  @auther          Alex Tan
 *  @date            2017/7/19
 *  @description     业主列表与业主申请列表的页面
 *  @param           applyType : applying表示业主申请界面
 */

class QueryOwner extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            owners: [''],
            isEnable: true,
            ownerCode: ''
        };
        this.page = 1;
        this.acceptFileTypes = ["xlsx", "xlsb", "xlsm", "xls", "csv"].map(function (x) {
            return "." + x;
        }).join(",");
        this.unitAliasData = {};
        this.unitsNum = {};
        this.unitsFloorNum = {};
        this.unitsRoomNum = {};
    }

    /*custom functions */
    search() {
        this.refs.table.refresh();
    }

    /* 判断当前页面显示业主列表还是申请列表 */
    isOwner() {
        return this.props.applyType != "applying";
    }

    synch(ownerCode) {
        postJson("/owner/synchOwner.x", {ownerCode: ownerCode}, () => {
            layui.layer.confirm("同步后请过一段时间刷新页面查看是否同步成功！", (index) => {
                layui.layer.close(index);
            });
        });
    }

    modify(ownerCode) {
        postJson("/owner/getOwner.x", {ownerCode: ownerCode}, (data) => {
            this.state.owner = data.data;
            this.refs.forSaveOwner.setState({owner: data.data});
        });

        this.refs.modalModify.show();
    }

    delete(ownerCode) {
        layui.layer.confirm("确定删除么?", (index) => {
            postJson("/owner/remove.x", {ownerCode: ownerCode}, (data) => {
                layui.layer.msg(data.data);
                this.refs.table.refresh();
            });
            layui.layer.close(index);
        });
    }

    view(ownerCode) {
        this.refs.modalView.show({typeData: '/pages/business/owner/view.html?ownerCode=' + ownerCode});
    }

    pass(ownerCode) {
        layui.layer.confirm("确定通过其为业主么?", (index) => {
            postJson("/owner/approveOwner.x", {ownerCode: ownerCode}, (data) => {
                layui.layer.msg(data.data);
                this.refs.table.refresh();
            });
            layui.layer.close(index);
        })
    }

    reject(ownerCode) {
        layui.layer.confirm("确定打回该请求么?", (index) => {
            let params = {ownerCode: ownerCode};
            postJson("/owner/reject.x", $.param(params), (data) => {
                layui.layer.msg(data.data);
                this.refs.table.refresh();
            });
            layui.layer.close(index);
        })
    }

    /* custom end */

    updateOwnerList(page, pageSize) {
        let params = {};
        params.page = page;
        params.pageSize = pageSize;
        let nameOrPhone = this.refs.nameOrPhone.value;
        let regex = /^[0-9]{11}$/;
        if (regex.test(nameOrPhone))
            params.ownerMob = nameOrPhone;
        else
            params.ownerName = nameOrPhone;

        params.commCode = this.refs.commSelect.commCode;
        params.areaCode = this.refs.commSelect.buildingCode;
        params.buildingCode = this.refs.commSelect.unitCode;
        params.unitCode = this.refs.commSelect.floorCode;
        params.roomCode = this.refs.commSelect.roomCode;

        if (!this.isOwner())
            params.applyType = 1;

        postJson("/owner/getOwnerList.x", $.param(params), (data) => {
            this.pageCount = data.data.size;
            this.setState({owners: data.data.list});

        })
    }

    batchDel() {
        console.log(this.refs.table.checkboxValue);
        if (this.refs.table.checkboxValue.length == 0) {
            layui.layer.msg("请选中一条数据");
            return;
        }
        layui.layer.confirm("确认要删除选中的" + this.refs.table.checkboxValue.length + "条业主信息么?", () => {
            postRJson("/owner/removeBatchs.x", JSON.stringify(this.refs.table.checkboxValue), () => {
                layui.layer.msg("删除成功!");
                this.refs.table.refresh();
            })
        });
    }

    /**
     * 导入excel表
     * 使用SheetJs将excel文件转换成json数组上传
     */
    importExcel() {
        console.log("importExcel");
        if (!this.refs.commSelect.commCode) {
            layui.layer.msg("请选择小区");
            return;
        }

        postJson("/building/getUnitsInfoForExport.x", {commCode: this.refs.commSelect.commCode}, (data) => {
            let buildings = data.data;
            /* 将楼栋与别名的映射关系转成map */
            for (let i = 0; i < buildings.length; i++) {
                /* 楼栋与别名的映射关系 */
                this.unitAliasData[buildings[i].areaName] = buildings[i].areaAliasName;

                /* 每个楼栋最大的单元数 */
                if (!this.unitsNum[buildings[i].areaName] || parseInt(this.unitsNum[buildings[i].areaName]) < parseInt(buildings[i].unitName))
                    this.unitsNum[buildings[i].areaName] = buildings[i].unitName;

                /* 每个单元最大的楼层数 */
                this.unitsFloorNum[buildings[i].areaName + '-' + buildings[i].unitName] = buildings[i].floorNum;
                /* 每个单元最大房间数 */
                this.unitsRoomNum[buildings[i].areaName + '-' + buildings[i].unitName] = buildings[i].roomNum;
            }

        });
        console.log("importExcel2");
        this.refs.import.importExcel();
    }

    /**
     * 导出excel表
     * 用到SheetJs，纯前端转换成excel文件
     */
    exportExcel() {
        if (!this.refs.commSelect.commCode) {
            layui.layer.msg("请选择小区");
            return;
        }

        let confirmStr = "确认要导出【" + this.refs.commSelect.commText + "】" +
            (this.refs.commSelect.buildingCode.length > 0 ? this.refs.commSelect.buildingText : '') +
            (this.refs.commSelect.unitCode.length > 0 ? this.refs.commSelect.unitText : '') +
            (this.refs.commSelect.floorCode.length > 0 ? this.refs.commSelect.floorCode : '') +
            (this.refs.commSelect.roomCode.length > 0 ? this.refs.commSelect.roomCode : '') + "的业主数据么?";

        layui.layer.confirm(confirmStr, (index) => {
            let params = {};
            params.commCode = this.refs.commSelect.commCode;
            params.areaCode = this.refs.commSelect.buildingCode;
            params.buildingCode = this.refs.commSelect.unitCode;
            params.unitCode = this.refs.commSelect.floorCode;
            params.roomCode = this.refs.commSelect.roomCode;
            this.refs.export.exportExcel("/owner/getOwnerListForExport.x", params, this.ownerJsonObj2JsonArray);
            layui.layer.close(index);
        });
    }

    /**
     * 将json对象数组转换成二维数组，因为对象中的key对excel来说是没有意义的
     * 如果直接传入对象数组，会造成浏览器卡死!
     * @param owners 服务端下来的业主对象数组
     * @returns {Array}
     */
    ownerJsonObj2JsonArray(owners) {
        let retArray = [];
        let titleArr = ['业主名称', '业主手机号', '业主楼栋编号', '业主楼栋信息'];
        retArray.push(titleArr);
        for (let i = 0; i < owners.length; i++) {
            let tempArr = [];
            tempArr.push(owners[i].ownerName);
            tempArr.push(owners[i].ownerMob);
            tempArr.push(owners[i].roomInfoNum.substr(4, 12));
            tempArr.push(owners[i].roomInfo);
            retArray.push(tempArr);
        }

        return retArray;
    }

    dataCheck(line, tempArr) {
        if (tempArr[1].length != 11) {
            layui.layer.alert("第" + line + "行数据" + tempArr[1] + "错误<br>请检查是否为手机号", {title: "格式不对"});
            return false;
        } else if (tempArr[2].length != 8) {
            layui.layer.alert("第" + line + "行数据" + tempArr[2] + "错误<br>范例:01010101(含义:01栋01单元01楼01号房)", {title: "格式不对"});
            return false;
        }
        return true;
    }

    buildingCheck(area, unit, floor, room, buildingStr) {

        if (!this.unitAliasData.hasOwnProperty(parseInt(area) + '')) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + area + "楼栋不存在!");
            return false;
        }
        if (parseInt(unit) > this.unitsNum[parseInt(area) + '']) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + unit + "单元不存在!");
            return false;
        }
        if (parseInt(floor) > this.unitsFloorNum[parseInt(area) + '-' + parseInt(unit)]) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + floor + "楼层不存在! 该单元最高" + this.unitsFloorNum[parseInt(area) + '-' + parseInt(unit)] + "层!");
            return false;
        }
        if (parseInt(room) > this.unitsRoomNum[parseInt(area) + '-' + parseInt(unit)]) {
            layui.layer.alert('业主楼栋编号' + buildingStr + '错误! ' + room + "房号不存在!<br>该单元楼层最大房号数目" + this.unitsRoomNum[parseInt(area) + '-' + parseInt(unit)]);
            return false;
        }

        return true;
    }


    importDataHandle(data) {

        let titleArr = data[0];
        if (titleArr[0] != '业主名称' || titleArr[1] != '业主手机号' || titleArr[2] != '业主楼栋编号') {
            layui.layer.alert("excel表单第一行三个字段的值必须是<br>业主名称、业主手机号、业主楼栋编号", {title: "格式不对"});
            return;
        }


        let uploadArr = [];
        for (let i = 1; i < data.length; i++) {
            let tempArr = data[i];

            if (tempArr.length == 0)
                continue;

            if (!this.dataCheck(i + 1, tempArr))
                return;

            let areaName = tempArr[2].substr(0, 2);
            let unitName = tempArr[2].substr(2, 2);
            let floor = tempArr[2].substr(4, 2);
            let room = tempArr[2].substr(6, 2);

            if (!this.buildingCheck(areaName, unitName, floor, room, tempArr[2]))
                return;

            let commName = this.refs.commSelect.commText;
            let commCode = $.trim(this.refs.commSelect.commCode);
            let owner = {
                ownerName: tempArr[0],
                ownerMob: tempArr[1],
                roomInfoNum: commCode + tempArr[2],
                commCode: commCode,
                commName: commName,
                areaCode: areaName,
                buildingCode: unitName,
                unitCode: floor,
                roomId: room,
                roomInfo: '[' + commName + '] ' + this.unitAliasData[parseInt(areaName) + ''] + ' ' + unitName + "单元 " + floor + "楼 " + room + "房",
            }

            uploadArr.push(owner);
        }

        layui.layer.confirm("确定导入此" + uploadArr.length + "条数据么?", (index) => {
            postRJson("/owner/saveBatchsOwner.x", JSON.stringify(uploadArr), (data) => {
                layui.layer.msg(data.data);
                this.refs.import.clearData();
                this.refs.table.refresh();
                layui.layer.close(index);
            });
        });

    }

    commChange() {
        this.search();
    }

    checkboxOnClick(data, owner) {
        console.log("data", data, "owner", owner)
        this.setState({
            isEnable: data,
            ownerCode: owner.ownerCode
        }, () => {
            this.refs.modal_permission_config.show();
        });
        this.refs.callPermission.checked = data;
        this.refs.facePermission.checked = data;
        this.refs.icPermission.checked = data;
        /*layer.confirm(data === true ? '确定要启用这个业主吗？启用后该业主就能使用开锁、监视等功能。' :
            '确定要禁止这个业主吗？禁止后该业主将不能使用开锁、监视等功能！', {
            btn: ['确定', '取消'] //按钮
        }, (index) => {
            let params = {};
            params.ownerCode = owner.ownerCode;
            params.isEnable = data === true ? 0 : 1;
            console.log("params", params)
            postJson("/owner/updateState.x", params, (data) => {
                layui.layer.msg(data.data);
                this.refs.table.refresh();
                layer.close(index);
            });
        }, () => {
            this.setState({});
        });*/
    }

    enableOwner(isOk) {
        if (isOk) {
            let params = {};
            params.ownerCode = this.state.ownerCode;
            params.isEnable = this.state.isEnable === true ? 0 : 1;
            params.callPermission = this.refs.callPermission.checked;
            params.facePermission = this.refs.facePermission.checked;
            params.icPermission = this.refs.icPermission.checked;
            console.log("params", params)
            postJson("/owner/updateState.x", params, (data) => {
                layui.layer.msg(data.data);
                this.refs.table.refresh();
                this.refs.modal_permission_config.close();
            });
        } else {
            this.refs.modal_permission_config.close();
        }
    }

    render() {
        let ownerStyle = this.isOwner() ? {} : {display: "none"};
        let applyingStyle = !this.isOwner() ? {} : {display: "none"};
        return (
            <Frame header="业主列表">
                <Form type="pane">
                    <Item>
                        <Label width="hg">业主名称或手机号</Label>
                        <Input ref="nameOrPhone"/>
                        <LayuiCommSelect firstValue={hasRoles("admin") ? '所有小区' : ''} formLabelName="楼栋信息"
                                         ref="commSelect" onChangeComm={(comm) => this.commChange(comm)}/>
                        <Button btnType="normal" onClick={() => this.search()}>查询</Button>
                    </Item>

                    <Table ref="table" count={this.pageCount}
                           checkboxRenderCallback={() => {
                               this.setState({})
                           }}
                           checkboxKeyname="ownerCode"
                           pageData={this.state.owners}
                           pageOnClick={(page, pageSize) => this.updateOwnerList(page, pageSize)}
                           toolbar={
                               [
                                   <Button className="pull-left" btnType="danger" size="sm" style={{marginRight: 5}}
                                           onClick={() => this.batchDel()}>批量删除</Button>,
                                   this.isOwner() ?
                                       <FileImportButton
                                           ref="import"
                                           onClick={() => this.importExcel()}
                                           dataCallBack={(data) => this.importDataHandle(data)}
                                       >Excel导入
                                       </FileImportButton> : '',
                                   this.isOwner() ?
                                       <FileExportButton
                                           ref="export"
                                           exportFileName="业主信息表"
                                           onClick={() => this.exportExcel()}
                                       >Excel导出
                                       </FileExportButton> : ''
                               ]
                           }
                    >
                        <thead>
                        <tr>
                            <th width={70}><TCheckbox checkall="true" tableRef={this.refs.table}/></th>
                            <th>门牌编号</th>
                            <th>业主名称</th>
                            <th>业主类型</th>
                            <th>手机号</th>
                            <th style={ownerStyle}>最后修改时间</th>
                            {hasPermsLanMode() ?
                                <th width={70}><Button size="xs"
                                                       onClick={ownerCode => this.synch()}>点击同步</Button></th> : ''}
                            <th width={70}>是否启用</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {
                            this.state.owners.map((owner) => {
                                console.log("------------------->     "+owner.isSynch);
                                return <tr>
                                    <td><TCheckbox data={owner} tableRef={this.refs.table}/></td>
                                    <td>{owner.roomInfo}</td>
                                    <td>{owner.ownerName}</td>
                                    <td>{owner.applyType === 2 ? '家属' : owner.applyType === 5 ? '租客' : '业主'}</td>
                                    <td>{owner.ownerMob}</td>
                                    <td style={ownerStyle}>{owner.lastModify}</td>
                                    {hasPermsLanMode() ? <td>{owner.isSynch === 1 ? '已同步' : '未同步'}</td> : ''}
                                    <td>
                                        <Switch onClick={(data) => this.checkboxOnClick(data, owner)}
                                                checked={owner.isEnable !== 1}
                                                lay-text="启用|禁用"/>
                                    </td>
                                    <td>
                                        <Button btnType="normal" size="xs"
                                                onClick={ownerCode => this.modify(owner.ownerCode)} style={ownerStyle}>修改</Button>
                                        <Button btnType="danger" size="xs"
                                                onClick={ownerCode => this.delete(owner.ownerCode)}>删除</Button>
                                        <Button size="xs" onClick={ownerCode => this.view(owner.ownerCode)}
                                                style={ownerStyle}>查看</Button>
                                        <Button size="xs" onClick={ownerCode => this.pass(owner.ownerCode)}
                                                style={applyingStyle}>通过</Button>
                                        <Button btnType="warm" size="xs"
                                                onClick={ownerCode => this.reject(owner.ownerCode)}
                                                style={applyingStyle}>打回</Button>
                                    </td>
                                </tr>
                            })
                        }
                        </tbody>
                    </Table>
                </Form>
                <Modal title="业主信息" ref="modalView" modalType="iframe" area={['800px']}/>
                <Modal title="修改业主信息" ref="modalModify" area={['1157px']}>
                    <ForSaveOwner modify="true" ref="forSaveOwner" onComplete={() => {
                        this.refs.modalModify.close();
                        this.refs.table.refresh();
                    }}/>
                </Modal>

                <Modal
                    title="权限禁用获启用配置"
                    ref="modal_permission_config">
                    <Form size="sm">
                        <Item>
                            <Label width="hg">呼叫权限</Label>
                            <Switch ref="callPermission"
                                    lay-text="启用|禁用"/>
                        </Item>
                        <Item>
                            <Label width="hg">人脸识别权限</Label>
                            <Switch ref="facePermission"
                                    lay-text="启用|禁用"/>
                        </Item>
                        <Item>
                            <Label width="hg">IC卡权限</Label>
                            <Switch ref="icPermission"
                                    lay-text="启用|禁用"/>
                        </Item>
                        <Item>
                            <Button formBtn={true}
                                    style={{width: '80px'}}
                                    size='sm'
                                    btnType='normal'
                                    onClick={() => this.enableOwner(true)}>确定</Button>
                            <Button style={{width: '80px'}}
                                    size='sm'
                                    btnType='primary'
                                    onClick={() => this.enableOwner(false)}>取消</Button>
                        </Item>
                    </Form>
                </Modal>
            </Frame>
        )
    }

}

ReactDOM.render(<QueryOwner applyType={$.query.get("applyType")}/>, document.getElementById("queryOwner"));